<template>
  <div class="modal-overlay" @click="handleOverlayClick">
    <div class="modal-container" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">新建任务</h3>
        <button class="modal-close-btn" @click="closeModal">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="handleCreateTask">
          <!-- 任务名称 -->
          <div class="form-item">
            <label class="form-label required">任务名称</label>
            <input 
              type="text" 
              class="input form-control" 
              v-model="taskForm.title" 
              placeholder="请输入任务名称"
              required
            >
          </div>
          
          <!-- 任务描述 -->
          <div class="form-item">
            <label class="form-label">任务描述</label>
            <textarea 
              class="textarea form-control" 
              v-model="taskForm.description" 
              placeholder="请输入任务描述（可选）"
              rows="3"
            ></textarea>
          </div>
          
          <!-- 数据源配置 -->
          <div class="form-item">
            <label class="form-label required">数据源配置</label>
            <select 
              class="select form-control" 
              v-model="taskForm.dataSource"
              required
            >
              <option value="">请选择数据源配置</option>
              <option v-for="source in dataSources" :key="source.id" :value="source.id">
                {{ source.name }}
              </option>
            </select>
          </div>
          
          <!-- 流程定义 -->
          <div class="form-item">
            <label class="form-label required">流程定义</label>
            <select 
              class="select form-control" 
              v-model="taskForm.processDefinition"
              required
            >
              <option value="">请选择流程定义</option>
              <option v-for="process in processes" :key="process.id" :value="process.id">
                {{ process.name }}
              </option>
            </select>
          </div>
        </form>
      </div>
      
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeModal">取消</button>
        <button class="btn btn-primary" @click="handleCreateTask">创建任务</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { createTask } from '../services/taskService';

export default {
  name: 'NewTaskModal',
  emits: ['close', 'created'],
  setup(props, { emit }) {
    const taskForm = ref({
      title: '',
      description: '',
      dataSource: '',
      processDefinition: ''
    });
    
    // 模拟数据源配置列表
    const dataSources = ref([
      { id: 'ds1', name: 'MySQL 数据源' },
      { id: 'ds2', name: 'PostgreSQL 数据源' },
      { id: 'ds3', name: 'MongoDB 数据源' }
    ]);
    
    // 模拟流程定义列表
    const processes = ref([
      { id: 'proc1', name: '标准审批流程' },
      { id: 'proc2', name: '快速部署流程' },
      { id: 'proc3', name: '测试验证流程' }
    ]);
    
    // 关闭模态框
    const closeModal = () => {
      emit('close');
    };
    
    // 处理点击遮罩层
    const handleOverlayClick = () => {
      closeModal();
    };
    
    // 处理创建任务
    const handleCreateTask = async () => {
      if (!taskForm.value.title || !taskForm.value.dataSource || !taskForm.value.processDefinition) {
        alert('请填写所有必填项');
        return;
      }
      
      try {
        // 调用真实的创建任务API
        const newTask = await createTask({
          title: taskForm.value.title,
          description: taskForm.value.description,
          taskType: '自定义任务', // 添加任务类型
          department: '默认部门', // 添加部门信息
          application: '',
          repository: ''
        });

        // 重置表单
        taskForm.value = {
          title: '',
          description: '',
          dataSource: '',
          processDefinition: ''
        };

        // 关闭模态框并通知父组件任务已创建，同时传递新创建的任务数据
        emit('created', newTask);
        closeModal();

        // 显示成功提示
        alert('任务创建成功！');
      } catch (error) {
        console.error('创建任务失败:', error);
        
        // 创建模拟任务，确保用户的任务能够显示
        const mockNewTask = {
          id: Date.now().toString(),
          title: taskForm.value.title,
          description: taskForm.value.description,
          taskType: '自定义任务',
          department: '默认部门',
          status: 'pending',
          createdAt: new Date().toISOString(),
          dataSource: taskForm.value.dataSource,
          processDefinition: taskForm.value.processDefinition
        };
        
        // 重置表单
        taskForm.value = {
          title: '',
          description: '',
          dataSource: '',
          processDefinition: ''
        };
        
        // 通知父组件任务已创建，传递模拟的任务数据
        emit('created', mockNewTask);
        closeModal();
        
        // 显示提示，但仍然显示任务已创建
        alert('任务已添加到列表（离线模式）！');
      }
    };
    
    // 在实际项目中，这里可以获取真实的数据源配置和流程定义列表
    onMounted(() => {
      // 模拟获取数据
      // fetchDataSources();
      // fetchProcessDefinitions();
    });
    
    return {
      taskForm,
      dataSources,
      processes,
      closeModal,
      handleOverlayClick,
      handleCreateTask
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-lg);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-lg);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-light);
}

.modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.modal-close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius-base);
  transition: background-color 0.3s ease;
}

.modal-close-btn:hover {
  background-color: var(--bg-hover);
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
}

.form-control {
  width: 100%;
}

.required::after {
  content: ' *';
  color: var(--danger-color);
}

.textarea {
  width: 100%;
  padding: var(--spacing-md);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  font-family: inherit;
  resize: vertical;
  transition: all 0.3s ease;
  background-color: var(--bg-white);
  color: var(--text-primary);
}

.textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

.textarea::placeholder {
  color: var(--text-placeholder);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid var(--border-light);
  background-color: var(--bg-light);
  border-bottom-left-radius: var(--border-radius-lg);
  border-bottom-right-radius: var(--border-radius-lg);
}
</style>